package lua_engine

import (
	"fmt"
	lua "github.com/yuin/gopher-lua"
)

func RunScript(scriptStr string) error {
	L := lua.NewState()
	defer L.Close()

	registerFun(L)

	err := L.DoString(scriptStr)
	if err != nil {
		return err
	}
	return nil
}

func RunFile(filePath string) error {
	L := lua.NewState()
	defer L.Close()

	registerFun(L)

	err := L.DoFile(filePath)
	if err != nil {
		return err
	}

	return nil
}

func _setValue(L *lua.LState) int {
	key := L.ToString(1)
	val := L.ToNumber(2)
	//todo

	res := key + val.String()

	L.Push(lua.LString(res))
	fmt.Println("lua_engine.go   pring $$$$$$$$$" + res + "$$$$$$$$$$$$$$$")
	//返回值个数
	return 1
}

func registerFun(L *lua.LState) {
	// 注册全局函数
	L.SetGlobal("setValue", L.NewFunction(_setValue))
}
